package com.example.pcmonitor.task;

import com.alibaba.fastjson.JSON;
import com.example.pcmonitor.bean.ProcessInfo;
import com.example.pcmonitor.server.WebSocketServer;
import com.example.pcmonitor.util.OsUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.NumberFormat;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class MyTask {
    //3.添加定时任务(每隔五秒)
    @Scheduled(cron = "0/5 * * * * ?")
//    @Scheduled(cron = "*/1 * * * * ?")

    //或直接指定时间间隔，例如：5秒
    //@Scheduled(fixedRate=5000)
    private void configureTasks() {
        NumberFormat nf = NumberFormat.getNumberInstance();
        /**
         * setMaximumFractionDigits(int newValue)
         设置数的小数部分所允许的最大位数。
         */
        try{
            Double cpuUsage= OsUtils.cpu();
            Double storageUsage = OsUtils.storage();
            Double memoryUsage = OsUtils.memory();
            List<ProcessInfo> processInfo = OsUtils.getProcessInfo();
            Map result=new HashMap();
            result.put("cpuUsage",Double.parseDouble(nf.format(cpuUsage)));
            result.put("memoryUsage",Double.parseDouble(nf.format(memoryUsage*100)));
            result.put("storageUsage",Double.parseDouble(nf.format(storageUsage)));
            result.put("process",processInfo);
            WebSocketServer.sendInfo(JSON.toJSONString(result),"1");
        }catch (Exception e){
            e.printStackTrace();
        }
        System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
    }
}
